import Taro from "@tarojs/taro";
import { auth } from "./auth-service";

const interceptor = chain =>
  chain.proceed(chain.requestParams).then(async res => {
    if (res.statusCode === 401) {
      const loginResult = await Taro.login();
      const authResult = await auth(loginResult.code);
      Taro.setStorageSync("sessionKey", authResult.data.data.sessionKey);

      // 重新发起请求
      const requestParams = chain.requestParams;
      const { method, data, url } = requestParams;
      return request(url, data, method);
    } else {
      return res;
    }
  });

Taro.addInterceptor(interceptor);

/**
 *
 * @param url
 * @param methods 默认 GET 请求
 * @param data
 */
export const request = (
  url: string,
  data?: Object,
  method: "POST" | "GET" | "PUT" | "DELETE" = "GET"
) => {
  const sessionKey = Taro.getStorageSync("sessionKey");
  return Taro.request({
    url,
    data,
    method,
    header: {
      "Auth-Token": sessionKey
    }
  });
};
